﻿using System;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using ExcellentCRM.DataService;
using ExcellentCRM.DataService.Models;
using ExcellentCRM.Site.Exts;
using ExcellentCRM.Site.Filters;
using ExcellentCRM.Site.Utilities;

namespace ExcellentCRM.Site.Controllers
{
    [SiteAuth]
    public class BaseController : AsyncController
    {
        private readonly Lazy<ServiceFactory> _lazyServiceFactory =
            new Lazy<ServiceFactory>(() => new ServiceFactory());
        protected ServiceFactory ServiceFactory
        {
            get { return _lazyServiceFactory.Value; }
        }

        private Account _currentUserAcct;

        protected Account CurrentUserAcct
        {
            get
            {
                if (_currentUserAcct == null)
                {
                    long acctId;
                    var sessionAcctId = Session[PresetValues.SessionKeys.CurrentAcctId];
                    if (sessionAcctId != null && long.TryParse(sessionAcctId.ToString(), out acctId))
                        _currentUserAcct = ServiceFactory.AcctService.GetModel(acctId);
                }
                return _currentUserAcct;
            }
        }

        /// <summary>
        /// 当前登录用户Id
        /// </summary>
        protected long CurrentStaffId
        {
            get
            {
                var currentStaff = CurrentUserAcct.Staff.FirstOrDefault();
                return currentStaff == null ? -1 : currentStaff.Id;
            }
        }

        protected string ActiveAct
        {
            get
            {
                return ViewData.ContainsKey(PresetValues.ViewDataKeys.ActiveAct)
                           ? ViewData[PresetValues.ViewDataKeys.ActiveAct].ToString()
                           : null;
            }
            set { ViewData[PresetValues.ViewDataKeys.ActiveAct] = value; }
        }

        protected override JsonResult Json(object data, string contentType,
                                           Encoding contentEncoding, JsonRequestBehavior behavior)
        {
            return new JsonNetResult
                {
                    Data = data,
                    ContentType = contentType,
                    ContentEncoding = contentEncoding,
                    JsonRequestBehavior = behavior
                };
        }

        protected virtual string ModelErrorStr
        {
            get
            {
                if (ModelState == null || !ModelState.Values.Any()) return null;
                return string.Join("\r\n", ModelState.Values.Where(p => p.Errors.Any()).Select(
                    p => string.Join(",", p.Errors.Select(e => e.ErrorMessage))));
            }
        }

        protected override void OnActionExecuted(ActionExecutedContext filterCtx)
        {
            base.OnActionExecuted(filterCtx);
            if (string.IsNullOrWhiteSpace(ActiveAct))
                ActiveAct =
                    string.Format("{0}_{1}",
                                  filterCtx.ActionDescriptor.ControllerDescriptor.ControllerName,
                                  filterCtx.ActionDescriptor.ActionName);
        }
    }
}
